package net.llz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import net.llz.enums.BizCodeEnum;
import net.llz.enums.SendCodeEnum;
import net.llz.fegin.CouponFeignService;
import net.llz.interceptor.LoginInterceptor;
import net.llz.mapper.UserMapper;
import net.llz.model.LoginUser;
import net.llz.model.UserDO;
import net.llz.request.NewUserCouponRequest;
import net.llz.request.UserLoginRequest;
import net.llz.request.UserRegisterRequest;
import net.llz.service.NotifyService;
import net.llz.service.UserService;
import net.llz.util.CommonUtil;
import net.llz.util.JWTUtil;
import net.llz.util.JsonData;
import net.llz.vo.UserVO;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CouponFeignService couponFeignService;


    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 邮箱验证码验证
     * 密码加密（TODO）
     * 账号唯一性检查(TODO)
     * 插入数据库
     * 新注册用户福利发放(TODO)
     * @param registerRequest
     * @return
     */
    @Override
    @GlobalTransactional
    public JsonData register(UserRegisterRequest registerRequest) {

        //验证码邮箱验证
        Boolean checkCode =false ;
        if (StringUtils.isNotBlank(registerRequest.getMail())){
            checkCode =notifyService.checkCode(SendCodeEnum.USER_REGISTER,registerRequest.getMail(), registerRequest.getCode());
        }
        if (!checkCode){
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);

        }

        UserDO userDO =new UserDO();
        BeanUtils.copyProperties(registerRequest,userDO);

        userDO.setCreateTime(new Date());
        userDO.setSlogan("新年新气象，从头开始");
        //设置密码     userDO.setPwd(registerRequest.getPwd());

        //设置密钥
        userDO.setSecret("$1$" + CommonUtil.getStringNumRandom(8));
        //密码+盐处理
        String cryptPwd = Md5Crypt.md5Crypt(registerRequest.getPwd().getBytes(),userDO.getSecret());
        userDO.setPwd(cryptPwd);
        //账号唯一性检查  TODO

       if (checkUnique(userDO.getMail())){
           int rows = userMapper.insert(userDO);
           log.info("row:{},注册成功",rows,userDO.toString());

           //新用户注册成功 发放福利 TODO
           userRegisterInitTask(userDO);
           return JsonData.buildSuccess();

       }else {
           return JsonData.buildResult(BizCodeEnum.ACCOUNT_REPEAT);

       }

        

    }

    /**
     * 1、根据Mail去找有没这记录
     * 2、有的话，则用秘钥+用户传递的明文密码，进行加密，再和数据库的密文进行匹配
     *
     * @param userLoginRequest
     * @return
     */

    @Override
    public JsonData login(UserLoginRequest userLoginRequest) {
        List<UserDO> userDOList = userMapper.selectList(new QueryWrapper<UserDO>().eq("mail",userLoginRequest.getMail()));

        if (userDOList != null && userDOList.size() ==1 ){
            //已经注册
            UserDO userDO = userDOList.get(0);
            String cryptpwd =Md5Crypt.md5Crypt(userLoginRequest.getPwd().getBytes(),userDO.getSecret());
            if (cryptpwd.equals(userDO.getPwd())){
                //登录成功，生成token  TODO
                LoginUser loginUser = new LoginUser();
                BeanUtils.copyProperties(userDO,loginUser);

                String accessToken = JWTUtil.geneJsonWebToken(loginUser);

                //accessToken的过期时间
                //UUID生成一个token
                //String refreshToken = CommonUtil.generateUUID();
                //redisTemplate.opsForValue().set(refreshToken,"1",1000*60*24*30);

                return JsonData.buildSuccess(accessToken);


            }else {

                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }
           // BeanUtils.copyProperties(userDO,lo);
        }else {
            //未注册
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }


    }

    @Override
    public UserVO findUserDetail() {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();

        UserDO userDO = userMapper.selectOne(new QueryWrapper<UserDO>().eq("id",loginUser.getId()));
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userDO,userVO);
        return userVO;
    }

    /**
     * 检测用户是否唯一
     * @param mail
     * @return
     */

    private boolean checkUnique(String mail ){
        QueryWrapper queryWrapper = new QueryWrapper<UserDO>().eq("mail",mail);
        List<UserDO> list = userMapper.selectList(queryWrapper);

        return  list.size()>0 ? false:true;
    }
    /**
     * 用户注册，初始化福利
     * @param userDO
     */
    private void userRegisterInitTask(UserDO userDO) {

        NewUserCouponRequest request = new NewUserCouponRequest();
        request.setName(userDO.getName());
        request.setUserId(userDO.getId());
       JsonData jsonData = couponFeignService.addNewUserCoupon(request);
       log.info("userdao信息{},jsondata信息{}",request.toString(),jsonData.toString());

    }
}
